<template>
  <div class="copy-text-wrapper">
    <span class="copy-text-content">
      <slot>{{ props.text }}</slot>
    </span>
    <a-button type="link" size="small" class="copy-btn" @click="handleCopy" :loading="copying">
      <template #icon>
        <div class="copy-icon">
          <CopyOutlined v-if="!copied" />
          <CheckOutlined v-else />
        </div>
      </template>
    </a-button>
  </div>
</template>

<script setup lang="ts">
import { ref } from 'vue'
import { message } from 'ant-design-vue'
import { CopyOutlined, CheckOutlined } from '@ant-design/icons-vue'

interface Props {
  // 要复制的文本内容，如果不传则使用插槽内容
  text?: string
}

const props = withDefaults(defineProps<Props>(), {
  text: ''
})

const copying = ref(false)
const copied = ref(false)

const handleCopy = async () => {
  if (copying.value) return

  copying.value = true

  try {
    let textToCopy = props.text

    // 如果没有传入text属性，则获取插槽内容
    if (!textToCopy) {
      const slotElement = document.querySelector('.copy-text-content')
      textToCopy = slotElement?.textContent || ''
    }

    if (!textToCopy) {
      message.warning('没有可复制的内容')
      return
    }

    await navigator.clipboard.writeText(textToCopy)

    copied.value = true
    message.success('复制成功')

    // 2秒后恢复图标状态
    setTimeout(() => {
      copied.value = false
    }, 2000)
  } catch (error) {
    console.error('复制失败:', error)
    message.error('复制失败')
  } finally {
    copying.value = false
  }
}
</script>

<style scoped>
.copy-text-wrapper {
  display: inline-flex;
  align-items: center;
  gap: 4px;
}

.copy-text-content {
  word-break: break-all;
}

.copy-btn {
  flex-shrink: 0;
  padding: 0 4px;
  height: auto;
  min-height: 20px;
  color: #666;
  transition: color 0.2s;
}

.copy-btn:hover {
  color: #1890ff;
}

/* .copy-icon {
  display: none;
}

.copy-text-wrapper:hover .copy-icon {
  display: block;
} */

.copy-icon {
  opacity: 0;
  transition: opacity 0.2s;
}

.copy-text-wrapper:hover .copy-icon {
  opacity: 1;
}

.copy-btn:focus {
  box-shadow: none;
}
</style>
